package com.item.controller;

import com.google.code.kaptcha.Producer;
import com.item.pojo.Auth;
import com.item.pojo.Result;
import com.item.pojo.User;
import com.item.service.item.RedisService;
import com.item.service.roleservice;
import com.item.service.userservice;
import com.item.utils.GetUsernameUtil;
import com.item.utils.JwtUtil;
import com.item.utils.Md5Util;
import com.item.utils.getcode;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.Pattern;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.parameters.P;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RequestMapping("/user")
@RestController
@Validated//参数效验框架
public class usercontroller {
    @Autowired
    private userservice userservice;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$") String password, int age, String sex, String phone, String idCard, String verificationCode, String email, String address) {
        String Code = redisTemplate.opsForValue().get(email);
        System.out.println(username);
        User user = userservice.getusername(username);
        System.out.println(user);
        if (user == null) {
            if (verificationCode.equals(Code)) {
                userservice.register(username, password, age, address, sex, phone, idCard, email);
                return Result.success();
            } else return Result.error("验证码错误");

        } else {
            return Result.error("已经存在用户");
        }

    }

    @PostMapping("/checkuser")
    public Result checkuser(String username) {
        System.out.println(username);
        User user = userservice.getusername(username);
        if (user == null) {
            return Result.success("true");
        } else {

            return Result.error("密码重复");
        }

    }

    @Autowired
    private RedisService redisService;

    @PostMapping("/sendcode")
    public Result sendcode(@Pattern(regexp = "^\\w+([-+.]\\w+)*@qq\\.com$", message = "邮箱格式不合法") String email) {
        String code;
        getcode getcode = new getcode();
        code = getcode.getcode1();
        if (redisService.saveVerificationCode(email, code).equals("true")) {
            return Result.success("发送成功，时效为五分钟");
        } else {
            return Result.error("发送失败");
        }
    }

    @Autowired
    private PasswordEncoder passwordEncoder;

    @PostMapping("/login")
    public Result userlogin(@Pattern(regexp = "^\\S{5,16}$", message = "账户格式不合法") String username, @Pattern(regexp = "^\\S{5,16}$", message = "密码格式不合法") String password, String captcha) {
        User user = userservice.getusername(username);
        if (user == null) {
            return Result.error("用户名错误");
        } else if (password.equals(user.getPassword())) {
            if (captcha.equals(redisTemplate.opsForValue().get("captcha"))) {
                Map<String, Object> claims = new HashMap<>();
                claims.put("id", user.getId());
                claims.put("username", user.getUsername());
                String token = JwtUtil.genToken(claims);
                System.out.println(token);
                return Result.success(token);
            } else return Result.error("验证码错误");

        } else {
            System.out.println(passwordEncoder.encode(password));
            return Result.error("密码错误");
        }
    }

    @Autowired
    private Producer captchaProducer;

    @GetMapping("/captcha")
    public void captcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");
        String captchaText = captchaProducer.createText();
        redisTemplate.opsForValue().set("captcha", captchaText);
        redisTemplate.expire("captcha", 5, TimeUnit.MINUTES);//存储在Redis中一个五分钟的验证码
        BufferedImage bufferedImage = captchaProducer.createImage(captchaText);

        ServletOutputStream outputStream = response.getOutputStream();
        ImageIO.write(bufferedImage, "jpg", outputStream);
        outputStream.flush();
        outputStream.close();
    }

    @PostMapping("/findusers")
    public Result finduser(String username) {

        System.out.println(username);
        User user = userservice.getusername(username);
        if (user != null) {
            return Result.success("user");
        } else return Result.error("权限认证失败");
    }

    @PutMapping("/userdetails")
    public Result UpdateUser(String password, Integer age) {
        String userid = redisTemplate.opsForValue().get("userid");
        System.out.println(userid);
        userservice.update(password, age, userid);
        return Result.success();

    }

    @PostMapping("/getUserInfo")
    public Result<List<User>> getUserInfo(@RequestHeader("Authorization")String token) {
        String username = GetUsernameUtil.getUsername(token);
        List<User> user = userservice.getUserInfo(username);
        return Result.success(user);
    }

    @PostMapping("/updateUserInfo")
    public Result updateUserInfo(String username,String email,Integer age,String phone,String idCard,String address,String sex) {
        Boolean is = userservice.updateUserInfo(username,email,age,phone,idCard,address,sex);
        if (!is){
            return Result.error("更新失败");
        }
        return Result.success();
    }

    @PostMapping("/updateUserAvatar")
    public Result updateUserAvatar(String username,String imageUrl) {
        System.out.println(username);
        Boolean is = userservice.updateUserAvatar(username,imageUrl);
        if (!is){
            return Result.error("更新失败");
        }
        return Result.success();
    }

}
